package com.zougen202301180355.restaurant.config;

import org.apache.ibatis.session.Configuration;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;
import java.io.IOException;

/**
 * @author 邹根
 * @date 2025/12/1
 *
 * MyBatis 配置类
 */
@org.springframework.context.annotation.Configuration
public class MyBatisConfig {

    @Bean
    public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource) throws IOException {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        sqlSessionFactoryBean.setTypeAliasesPackage("com.zougen202301180355.restaurant.pojo");
        
        // 配置 Mapper XML 文件的位置
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath:mapper/*.xml"));
        
        // 配置 MyBatis 设置（开启驼峰命名转换）
        Configuration configuration = new Configuration();
        configuration.setMapUnderscoreToCamelCase(true);  // 开启下划线转驼峰
        configuration.setCacheEnabled(true);  // 开启二级缓存
        sqlSessionFactoryBean.setConfiguration(configuration);
        
        return sqlSessionFactoryBean;
    }

    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer(){
        MapperScannerConfigurer msc = new MapperScannerConfigurer();
        msc.setBasePackage("com.zougen202301180355.restaurant.mapper");
        return msc;
    }

}